<template>
  <div class="data-board-container">
  
    <!-- 班主任视角：班级信息 -->
    <div class="class-info" v-if="userStore.loginUser.role === 0">
      <div class="class-icon">
        <el-icon :size="30"><school /></el-icon>
      </div>
      <div class="class-name">
        <h3>{{ getClassFullName() }}</h3>
      </div>
      <div class="filters">
        <div class="filter-item">
          <span class="filter-label">年度：</span>
          <el-select v-model="filters.year" placeholder="年度" style="width: 120px;" clearable @change="handleFilterChange">
            <el-option
              v-for="item in yearOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <span class="filter-label">性别：</span>
          <el-select v-model="filters.gender" placeholder="性别" style="width: 120px;" clearable @change="handleFilterChange">
            <el-option
              v-for="item in genderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-button type="primary" plain size="small" @click="clearFilters">
          <el-icon><refresh /></el-icon>
          清空条件
        </el-button>
      </div>
    </div>

    <!-- 校管理员或教育局管理员视角 -->
    <div class="region-info" v-else>

      <div class="region-container">
        <div class="region-icon">
          <el-icon :size="30"><office-building /></el-icon>
        </div>

        <div class="region-name">
           <h3>{{ userStore.loginUser.role === 1 ? schoolInfo.name : regionInfo.name }}</h3>
        </div>
      </div>
     

      <div class="filters">
        <el-select v-model="filters.year" placeholder="学年" @change="handleFilterChange">
          <el-option
            v-for="item in yearOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="filters.stage" placeholder="学段" v-if="userStore.loginUser.role === 2" @change="handleFilterChange">
          <el-option
            v-for="item in stageOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="filters.region" placeholder="区域" v-if="userStore.loginUser.role === 2" @change="handleFilterChange">
          <el-option
            v-for="item in regionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="filters.grade" placeholder="年级" v-if="userStore.loginUser.role === 1" @change="handleFilterChange">
          <el-option
            v-for="item in gradeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="filters.class" placeholder="班级" v-if="userStore.loginUser.role === 1" @change="handleFilterChange">
          <el-option
            v-for="item in classOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="filters.gender" placeholder="性别" @change="handleFilterChange">
          <el-option
            v-for="item in genderOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>

    <!-- 班主任视角：班级统计数据 -->
    <div class="class-stats" v-if="userStore.loginUser.role === 0">
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-label">学生总数</div>
          <div class="stat-value">{{ classStats.totalStudents }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">男生人数</div>
          <div class="stat-value">{{ classStats.maleStudents }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">女生人数</div>
          <div class="stat-value">{{ classStats.femaleStudents }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">测试项目</div>
          <div class="stat-value">{{ classStats.testItems }}</div>
        </div>
      </div>
    </div>

    <!-- 非班主任角色的概览 -->
    <div class="overview" v-if="userStore.loginUser.role !== 0">
      <div class="overview-title">概览</div>
      <div class="stats-overview">
        <div class="stat-card">
          <div class="label">学生总数</div>
          <div class="value">{{ statsData.totalStudents }}</div>
          <div class="rate-change" :class="{ 'rate-up': statsData.studentChange > 0, 'rate-down': statsData.studentChange < 0 }">
            {{ statsData.studentChange > 0 ? '+' : '' }}{{ statsData.studentChange }}%
          </div>
        </div>
        <div class="stat-card">
          <div class="label">合格人数</div>
          <div class="value">{{ statsData.qualifiedStudents }}</div>
          <div class="rate-change" :class="{ 'rate-up': statsData.qualifiedChange > 0, 'rate-down': statsData.qualifiedChange < 0 }">
            {{ statsData.qualifiedChange > 0 ? '+' : '' }}{{ statsData.qualifiedChange }}%
          </div>
        </div>
        <div class="stat-card">
          <div class="label">优秀人数</div>
          <div class="value">{{ statsData.excellentStudents }}</div>
          <div class="rate-change" :class="{ 'rate-up': statsData.excellentChange > 0, 'rate-down': statsData.excellentChange < 0 }">
            {{ statsData.excellentChange > 0 ? '+' : '' }}{{ statsData.excellentChange }}%
          </div>
        </div>
        <div class="stat-card">
          <div class="label">合格率</div>
          <div class="value">{{ statsData.qualificationRate }}%</div>
          <div class="rate-change" :class="{ 'rate-up': statsData.rateChange > 0, 'rate-down': statsData.rateChange < 0 }">
            {{ statsData.rateChange > 0 ? '+' : '' }}{{ statsData.rateChange }}%
          </div>
        </div>
      </div>
    </div>

    <!-- 班主任视角：体测指标合格率 -->
    <div class="teacher-charts" v-if="userStore.loginUser.role === 0">
      <div class="chart-card">
        <div class="chart-title">体测指标合格率</div>
        <div id="test-qualification-chart" class="chart"></div>
      </div>
      
      <div class="chart-card">
        <div class="chart-title">合格情况总览</div>
        <div class="qualification-overview">
          <div id="qualification-overview-chart" class="chart"></div>
          <div class="qualification-stats">
            <div class="qualification-stat">
              <div class="stat-dot not-qualified"></div>
              <div class="stat-label">未达标人数</div>
              <div class="stat-value">{{ classStats.notQualifiedStudents }}</div>
            </div>
            <div class="qualification-stat">
              <div class="stat-dot qualified"></div>
              <div class="stat-label">达标人数</div>
              <div class="stat-value">{{ classStats.qualifiedStudents }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="chart-card">
        <div class="chart-title">评级占比</div>
        <div id="rating-distribution-chart" class="chart"></div>
      </div>
    </div>

    <!-- 非班主任角色的图表 -->
    <div v-if="userStore.loginUser.role !== 0">
      <div class="chart-container">
        <div class="chart-card yearly-trend">
          <div class="chart-title">合格率年度趋势</div>
          <div id="yearly-trend-chart" class="chart"></div>
        </div>
        
        <div class="chart-card test-items">
          <div class="chart-title">各体测项目合格率</div>
          <div class="test-items-filter">
            <el-radio-group v-model="selectedTestItem" size="small">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button v-for="item in testItemOptions" :key="item" :label="item">{{ item }}</el-radio-button>
            </el-radio-group>
          </div>
          <div id="test-items-chart" class="chart"></div>
        </div>
      </div>

      <!-- 校级管理员视角：班级合格率对比 -->
      <div class="classes-container" v-if="userStore.loginUser.role === 1">
        <div class="chart-card classes-comparison">
          <div class="chart-title">班级合格率对比</div>
          <div class="classes-comparison-filter">
            <el-dropdown @command="handleTestItemChange">
              <span class="test-item-dropdown">
                {{ currentTestItem }} <el-icon><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="50米跑">50米跑</el-dropdown-item>
                  <el-dropdown-item command="坐位体前屈">坐位体前屈</el-dropdown-item>
                  <el-dropdown-item command="1分钟跳绳">1分钟跳绳</el-dropdown-item>
                  <el-dropdown-item command="肺活量">肺活量</el-dropdown-item>
                  <el-dropdown-item command="BMI">BMI</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div id="classes-comparison-chart" class="chart"></div>
          
          <div class="class-items">
            <div v-for="(item, index) in classesComparisonData" :key="index" class="class-item">
              <div class="class-name">{{ item.name }}</div>
              <div class="class-progress">
                <div class="progress-bar" :style="{ width: item.rate + '%', backgroundColor: getClassColor(index) }"></div>
              </div>
              <div class="class-rate">{{ item.rate }}%</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 校级管理员视角：评级分布 -->
      <div class="chart-container" v-if="userStore.loginUser.role === 1">
        <div class="chart-card grade-distribution">
          <div class="chart-title">评级分布</div>
          <div id="grade-distribution-chart" class="chart"></div>
        </div>
        
        <div class="chart-card gender-comparison">
          <div class="chart-title">男女生体测对比</div>
          <div id="gender-comparison-chart" class="chart"></div>
        </div>
      </div>

      <!-- 教育局管理员视角：区域对比 -->
      <div class="regions-container" v-if="userStore.loginUser.role === 2">
        <div class="chart-card regions-comparison">
          <div class="chart-title">各区县合格率对比</div>
          <div class="regions-comparison-filter">
            <el-dropdown @command="handleTestItemChange">
              <span class="test-item-dropdown">
                {{ currentTestItem }} <el-icon><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="50米跑">50米跑</el-dropdown-item>
                  <el-dropdown-item command="坐位体前屈">坐位体前屈</el-dropdown-item>
                  <el-dropdown-item command="1分钟跳绳">1分钟跳绳</el-dropdown-item>
                  <el-dropdown-item command="肺活量">肺活量</el-dropdown-item>
                  <el-dropdown-item command="BMI">BMI</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div id="regions-comparison-chart" class="chart"></div>
          
          <div class="region-items">
            <div v-for="(item, index) in regionsComparisonData" :key="index" class="region-item">
              <div class="region-name">{{ item.name }}</div>
              <div class="region-progress">
                <div class="progress-bar" :style="{ width: item.rate + '%', backgroundColor: getRegionColor(index) }"></div>
              </div>
              <div class="region-rate">{{ item.rate }}%</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount, nextTick } from 'vue';
import * as echarts from 'echarts';
import { Search, ArrowDown, OfficeBuilding, School, Refresh } from '@element-plus/icons-vue';
import { useUserStore } from '../stores/userStore';
import { getAreaListApi, getDataPanelRequiredInfoApi } from '../api/modules/datapanel';
import { useDataPanelSearchModel, useDataPanelModel } from '../models/dataPanelModel';

// 用户信息
const userStore = useUserStore();

// 获取数据模型
const { searchParams } = useDataPanelSearchModel();
const { dataPanelData, loading, resetData, updateData } = useDataPanelModel();

// 获取班级全称
const getClassFullName = () => {
  if (!userStore.loginUser) return '';
  
  const schoolName = userStore.loginUser.schoolName || '';
  const grade = userStore.loginUser.grade || '';
  const classVal = userStore.loginUser.classVal || '';
  
  return `${schoolName}${grade}年级${classVal}班`;
};

// 班主任视角的班级统计数据
const classStats = ref({
  totalStudents: 0,
  maleStudents: 0,
  femaleStudents: 0,
  testItems: 0,
  qualifiedStudents: 0,
  notQualifiedStudents: 0,
  qualificationRates: {},
  ratingDistribution: {
    '优秀': 0,
    '良好': 0,
    '及格': 0
  }
});

// 筛选条件
const filters = ref({
  year: new Date().getFullYear(),
  stage: null,
  region: null,
  gender: null,
  grade: null,
  class: null
});

// 将前端筛选条件转换为后端API所需参数
const getApiParams = () => {
  // 创建映射后端需要的参数对象
  const params = {
    year: filters.value.year,
    gender: filters.value.gender === 'male' ? 1 : (filters.value.gender === 'female' ? 2 : null),
    gradeId: filters.value.grade ? parseInt(filters.value.grade) : null,
    stage: filters.value.stage === 'primary' ? 1 : (filters.value.stage === 'middle' ? 2 : (filters.value.stage === 'high' ? 3 : null)),
    clazzId: filters.value.class ? parseInt(filters.value.class) : null,
    districtId: filters.value.region ? parseInt(filters.value.region) : null
  };
  
  // 移除值为null的属性
  Object.keys(params).forEach(key => {
    if (params[key] === null || params[key] === undefined) {
      delete params[key];
    }
  });
  
  return params;
};

// 清空筛选条件
const clearFilters = () => {
  filters.value = {
    year: new Date().getFullYear(),
    stage: null,
    region: null,
    gender: null,
    grade: null,
    class: null
  };
  
  // 重置后获取数据
  fetchDataPanelInfo();
};

// 动态生成最近五年的年份选项
const yearOptions = computed(() => {
  const currentYear = new Date().getFullYear();
  const years = [];
  
  for (let i = 0; i < 5; i++) {
    const year = currentYear - i;
    years.push({
      value: year.toString(),
      label: `${year}年`
    });
  }
  
  return years;
});

// 学段选项
const stageOptions = [
  { value: '', label: '全部' },
  { value: 'primary', label: '小学' },
  { value: 'middle', label: '初中' },
  { value: 'high', label: '高中' }
];

// 区域选项
const regionOptions = ref([
  { value: '', label: '全部' }
]);

// 获取区域列表数据
const fetchRegionOptions = async () => {
  try {
    const res = await getAreaListApi();
    console.log('获取区域列表返回数据:', res);
    
    // 后端直接返回数据数组而非包含code和data的对象
    if (Array.isArray(res)) {
      // 处理数组格式的响应
      const districts = res.filter(district => district && district.districtName && district.districtCode)
        .map(district => ({
          value: district.districtCode,
          label: district.districtName
        }));
      
      if (districts.length > 0) {
        regionOptions.value = [
          { value: '', label: '全部' },
          ...districts
        ];
        console.log('成功解析区域数据:', districts.length, '条记录');
      } else {
        console.warn('区域数据为空或格式不匹配');
      }
    } 
    // 处理标准返回格式 {code: 1, data: [...]} 或 {code: 200, data: [...]}
    else if (res && (res.code === 200 || res.code === 1) && Array.isArray(res.data)) {
      const districts = res.data.filter(district => district && district.districtName && district.districtCode)
        .map(district => ({
          value: district.districtCode,
          label: district.districtName
        }));
      
      if (districts.length > 0) {
        regionOptions.value = [
          { value: '', label: '全部' },
          ...districts
        ];
        console.log('成功解析区域数据:', districts.length, '条记录');
      } else {
        console.warn('区域数据为空或格式不匹配');
      }
    } 
    // 尝试处理其他可能的返回格式
    else if (res && res.districts && Array.isArray(res.districts)) {
      const districts = res.districts.filter(district => district && district.districtName && district.districtCode)
        .map(district => ({
          value: district.districtCode,
          label: district.districtName
        }));
      
      if (districts.length > 0) {
        regionOptions.value = [
          { value: '', label: '全部' },
          ...districts
        ];
        console.log('成功解析区域数据:', districts.length, '条记录');
      } else {
        console.warn('区域数据为空或格式不匹配');
      }
    } else {
      console.error('获取区域列表格式异常:', res);
    }
  } catch (error) {
    console.error('获取区域列表失败:', error);
  }
};

// 性别选项
const genderOptions = [
  { value: '', label: '全部' },
  { value: 'male', label: '男' },
  { value: 'female', label: '女' }
];

// 地区信息
const regionInfo = ref({
  name: '成都市教育局'
});

// 学校信息
const schoolInfo = ref({
  name: '成都市第一中学'
});

// 年级选项
const gradeOptions = [
  { value: '', label: '全部' },
  { value: '1', label: '一年级' },
  { value: '2', label: '二年级' },
  { value: '3', label: '三年级' },
  { value: '4', label: '四年级' },
  { value: '5', label: '五年级' },
  { value: '6', label: '六年级' },
  { value: '7', label: '初一' },
  { value: '8', label: '初二' },
  { value: '9', label: '初三' },
  { value: '10', label: '高一' },
  { value: '11', label: '高二' },
  { value: '12', label: '高三' }
];

// 班级选项
const classOptions = [
  { value: '', label: '全部' },
  { value: '1', label: '1班' },
  { value: '2', label: '2班' },
  { value: '3', label: '3班' },
  { value: '4', label: '4班' },
  { value: '5', label: '5班' },
  { value: '6', label: '6班' },
  { value: '7', label: '7班' },
  { value: '8', label: '8班' }
];

// 体测项目选项
const testItemOptions = ref([]);

// 当前体测项目
const currentTestItem = ref('50米跑');
const handleTestItemChange = (command) => {
  currentTestItem.value = command;
  initRegionsComparisonChart();
};

// 区域比较数据
const regionsComparisonData = ref([
  { name: '武侯区', rate: 95 },
  { name: '锦江区', rate: 92 },
  { name: '青羊区', rate: 90 },
  { name: '成华区', rate: 88 },
  { name: '金牛区', rate: 85 }
]);

// 班级比较数据
const classesComparisonData = ref([
  { name: '初一1班', rate: 96 },
  { name: '初一2班', rate: 94 },
  { name: '初一3班', rate: 92 },
  { name: '初一4班', rate: 90 },
  { name: '初一5班', rate: 88 }
]);

// 评级分布数据
const gradeDistributionData = ref({
  excellent: 25,
  good: 35,
  pass: 30,
  fail: 10
});

// 男女生对比数据
const genderComparisonData = ref({
  categories: ['BMI', '50米跑', '坐位体前屈', '1分钟跳绳', '肺活量'],
  male: [85, 92, 75, 80, 88],
  female: [80, 85, 90, 85, 75]
});

// 获取区域颜色
const getRegionColor = (index) => {
  const colors = ['#ff5b8f', '#4e82ff', '#26d0c1', '#97eb9a', '#fad589'];
  return colors[index % colors.length];
};

// 获取班级颜色
const getClassColor = (index) => {
  const colors = ['#ff5b8f', '#4e82ff', '#26d0c1', '#97eb9a', '#fad589', '#8e87d8', '#5eb9fb', '#f19ec2'];
  return colors[index % colors.length];
};

// 图表实例
let yearlyTrendChart = null;
let testItemsChart = null;
let regionsComparisonChart = null;
let testQualificationChart = null;
let qualificationOverviewChart = null;
let ratingDistributionChart = null;
let classesComparisonChart = null;
let gradeDistributionChart = null;
let genderComparisonChart = null;

// 获取数据看板信息
const fetchDataPanelInfo = async () => {
  loading.value = true;
  try {
    // 获取API所需参数
    const params = getApiParams();
    console.log('请求数据看板数据，参数:', params);
    
    const res = await getDataPanelRequiredInfoApi(params);
    if (res && res.data) {
      console.log('获取数据看板数据成功:', res.data);
      updateData(res.data);
      
      // 更新班主任视角的数据
      updateClassStats(res.data);
      
      // 更新非班主任角色的数据
      updateStatsData(res.data);
      
      // 数据更新后重绘图表
      nextTick(() => {
        initCharts();
      });
    }
  } catch (error) {
    console.error('获取数据看板数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 更新班主任视角的统计数据
const updateClassStats = (data) => {
  classStats.value = {
    totalStudents: data.studentTotalCount || 0,
    maleStudents: data.maleCount || 0,
    femaleStudents: data.femaleCount || 0,
    testItems: data.testItemCount || 0,
    qualifiedStudents: data.qualifiedCount || 0,
    notQualifiedStudents: data.unQualifiedCount || 0,
    qualificationRates: {},
    ratingDistribution: {
      '优秀': data.excellence || 0,
      '良好': data.good || 0,
      '及格': data.qualified || 0
    }
  };
  
  // 处理体测项合格率
  if (data.testItemPassingRate && Array.isArray(data.testItemPassingRate)) {
    data.testItemPassingRate.forEach(item => {
      if (item.testItemName && item.passRate) {
        classStats.value.qualificationRates[item.testItemName] = parseFloat(item.passRate) * 100;
      }
    });
  }
};

// 统计数据
const statsData = ref({
  totalStudents: 0,
  studentChange: 0,
  qualifiedStudents: 0,
  qualifiedChange: 0,
  excellentStudents: 0,
  excellentChange: 0,
  qualificationRate: 0,
  rateChange: 0,
  yearlyData: {
    years: [],
    rates: []
  },
  testItemsData: {}
});

// 更新非班主任角色的统计数据
const updateStatsData = (data) => {
  // 基础数据
  statsData.value.totalStudents = data.studentTotalCount || 0;
  statsData.value.qualifiedStudents = data.qualifiedCount || 0;
  statsData.value.excellentStudents = data.excellence || 0;
  
  // 计算合格率
  if (data.studentTotalCount > 0) {
    statsData.value.qualificationRate = ((data.qualifiedCount / data.studentTotalCount) * 100).toFixed(2);
  } else {
    statsData.value.qualificationRate = 0;
  }
  
  // 变化率暂时默认为0（后端未提供）
  statsData.value.studentChange = 0;
  statsData.value.qualifiedChange = 0;
  statsData.value.excellentChange = 0;
  statsData.value.rateChange = 0;
  
  // 处理年度数据
  if (data.recentFiveYearsQualifiedRate) {
    const years = Object.keys(data.recentFiveYearsQualifiedRate).sort();
    const rates = years.map(year => data.recentFiveYearsQualifiedRate[year] * 100);
    
    statsData.value.yearlyData = {
      years: years,
      rates: rates
    };
  }
  
  // 处理体测项合格率
  statsData.value.testItemsData = {};
  if (data.testItemPassingRate && Array.isArray(data.testItemPassingRate)) {
    data.testItemPassingRate.forEach(item => {
      if (item.testItemName && item.passRate) {
        statsData.value.testItemsData[item.testItemName] = parseFloat(item.passRate) * 100;
      }
    });
  }
  
  // 更新测试项目选项
  testItemOptions.value = Object.keys(statsData.value.testItemsData);
};

// 初始化班主任视角的体测指标合格率图表
const initTestQualificationChart = () => {
  const chartDom = document.getElementById('test-qualification-chart');
  if (!chartDom) return;
  
  testQualificationChart = echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Object.keys(classStats.value.qualificationRates),
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%',
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [
      {
        name: '合格率',
        type: 'bar',
        data: Object.values(classStats.value.qualificationRates),
        itemStyle: {
          color: function(params) {
            const colorList = ['#8e87d8', '#5eb9fb', '#fad589', '#97eb9a', '#f19ec2'];
            return colorList[params.dataIndex % colorList.length];
          },
          borderRadius: [4, 4, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}%',
          color: '#666'
        }
      }
    ]
  };
  
  testQualificationChart.setOption(option);
};

// 初始化合格情况总览图表
const initQualificationOverviewChart = () => {
  const chartDom = document.getElementById('qualification-overview-chart');
  if (!chartDom) return;
  
  qualificationOverviewChart = echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    color: ['#4e82ff', '#ccc'],
    series: [
      {
        name: '合格情况',
        type: 'pie',
        radius: ['60%', '80%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        data: [
          { value: classStats.value.qualifiedStudents, name: '达标人数' },
          { value: classStats.value.notQualifiedStudents, name: '未达标人数' }
        ]
      }
    ]
  };
  
  qualificationOverviewChart.setOption(option);
};

// 初始化评级占比图表
const initRatingDistributionChart = () => {
  const chartDom = document.getElementById('rating-distribution-chart');
  if (!chartDom) return;
  
  ratingDistributionChart = echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}% ({d}%)'
    },
    color: ['#ff5b8f', '#4e82ff', '#26d0c1'],
    series: [
      {
        name: '评级占比',
        type: 'pie',
        radius: '70%',
        center: ['50%', '50%'],
        data: [
          { value: classStats.value.ratingDistribution['优秀'], name: '优秀' },
          { value: classStats.value.ratingDistribution['良好'], name: '良好' },
          { value: classStats.value.ratingDistribution['及格'], name: '及格' }
        ],
        label: {
          formatter: '{b}: {c}%'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  
  ratingDistributionChart.setOption(option);
};

// 初始化合格率年度趋势图表
const initYearlyTrendChart = () => {
  const chartDom = document.getElementById('yearly-trend-chart');
  if (!chartDom) return;
  
  yearlyTrendChart = echarts.init(chartDom);
  
  // 获取近五年达标率数据
  const yearRateData = statsData.value.yearlyData || {};
  
  // 过滤掉未来年份数据
  const currentYear = new Date().getFullYear();
  const filteredYears = [];
  const filteredRates = [];
  
  if (Array.isArray(yearRateData.years) && Array.isArray(yearRateData.rates)) {
    yearRateData.years.forEach((year, index) => {
      if (parseInt(year) <= currentYear) {
        filteredYears.push(year);
        filteredRates.push(validateRate(yearRateData.rates[index]));
      } else {
        console.warn(`发现未来年份数据: ${year}`);
      }
    });
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}年: {c}%',
      axisPointer: {
        type: 'line'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: filteredYears,
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%',
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [
      {
        name: '合格率',
        type: 'line',
        data: filteredRates,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#4e82ff'
        },
        lineStyle: {
          width: 3,
          color: '#4e82ff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(78, 130, 255, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(78, 130, 255, 0.1)'
              }
            ]
          }
        }
      }
    ]
  };
  
  yearlyTrendChart.setOption(option);
};

// 初始化各体测项目合格率图表
const initTestItemsChart = () => {
  const chartDom = document.getElementById('test-items-chart');
  if (!chartDom) return;
  
  testItemsChart = echarts.init(chartDom);
  
  const items = Object.keys(statsData.value.testItemsData);
  const rates = Object.values(statsData.value.testItemsData);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: items,
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%',
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [
      {
        name: '合格率',
        type: 'bar',
        data: rates,
        itemStyle: {
          color: function(params) {
            const colorList = ['#8e87d8', '#5eb9fb', '#fad589', '#97eb9a', '#f19ec2'];
            return colorList[params.dataIndex % colorList.length];
          },
          borderRadius: [4, 4, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}%',
          color: '#666'
        }
      }
    ]
  };
  
  testItemsChart.setOption(option);
};

// 初始化各班级合格率对比图表
const initClassesComparisonChart = () => {
  const chartDom = document.getElementById('classes-comparison-chart');
  if (!chartDom) return;
  
  classesComparisonChart = echarts.init(chartDom);
  
  const data = classesComparisonData.value.map(item => validateRate(item.rate) * 100);
  const classes = classesComparisonData.value.map(item => item.name);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c}%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%',
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: classes,
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    series: [
      {
        name: '合格率',
        type: 'bar',
        data: data,
        itemStyle: {
          color: function(params) {
            return getClassColor(params.dataIndex);
          },
          borderRadius: [0, 4, 4, 0]
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}%',
          color: '#666'
        }
      }
    ]
  };
  
  classesComparisonChart.setOption(option);
};

// 初始化评级分布图表
const initGradeDistributionChart = () => {
  const chartDom = document.getElementById('grade-distribution-chart');
  if (!chartDom) return;
  
  gradeDistributionChart = echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}% ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: ['优秀', '良好', '及格', '不及格']
    },
    color: ['#ff5b8f', '#4e82ff', '#26d0c1', '#ccc'],
    series: [
      {
        name: '评级分布',
        type: 'pie',
        radius: '65%',
        center: ['50%', '45%'],
        data: [
          { value: gradeDistributionData.value.excellent, name: '优秀' },
          { value: gradeDistributionData.value.good, name: '良好' },
          { value: gradeDistributionData.value.pass, name: '及格' },
          { value: gradeDistributionData.value.fail, name: '不及格' }
        ],
        label: {
          formatter: '{b}: {c}%'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  
  gradeDistributionChart.setOption(option);
};

// 初始化男女生体测对比图表
const initGenderComparisonChart = () => {
  const chartDom = document.getElementById('gender-comparison-chart');
  if (!chartDom) return;
  
  genderComparisonChart = echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['男生', '女生'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: genderComparisonData.value.categories,
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%',
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [
      {
        name: '男生',
        type: 'bar',
        data: genderComparisonData.value.male,
        itemStyle: {
          color: '#4e82ff',
          borderRadius: [4, 4, 0, 0]
        }
      },
      {
        name: '女生',
        type: 'bar',
        data: genderComparisonData.value.female,
        itemStyle: {
          color: '#ff5b8f',
          borderRadius: [4, 4, 0, 0]
        }
      }
    ]
  };
  
  genderComparisonChart.setOption(option);
};

// 初始化各区县合格率对比图表
const initRegionsComparisonChart = () => {
  const chartDom = document.getElementById('regions-comparison-chart');
  if (!chartDom) return;
  
  regionsComparisonChart = echarts.init(chartDom);
  
  const data = regionsComparisonData.value.map(item => validateRate(item.rate) * 100);
  const regions = regionsComparisonData.value.map(item => item.name);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c}%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%',
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: regions,
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    series: [
      {
        name: '合格率',
        type: 'bar',
        data: data,
        itemStyle: {
          color: function(params) {
            const colors = ['#ff5b8f', '#4e82ff', '#26d0c1', '#97eb9a', '#fad589'];
            return colors[params.dataIndex % colors.length];
          },
          borderRadius: [0, 4, 4, 0]
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}%',
          color: '#666'
        }
      }
    ]
  };
  
  regionsComparisonChart.setOption(option);
};

// 验证百分比率值，确保在0-1之间
const validateRate = (rate) => {
  // 如果不是数字，返回0
  if (typeof rate !== 'number') return 0;
  
  // 如果已经是小数形式(0-1之间)，直接返回
  if (rate >= 0 && rate <= 1) return rate;
  
  // 如果是大于1的数值，假设是已经是百分比形式，转换为小数
  if (rate > 1 && rate <= 100) return rate / 100;
  
  // 如果是异常大的值，可能是错误数据，限制在合理范围内
  if (rate > 100) return 1;
  
  // 负数或其他情况，返回0
  return 0;
};

// 初始化图表
const initCharts = () => {
  if (userStore.loginUser.role === 0) {
    // 班主任视角图表
    initTestQualificationChart();
    initQualificationOverviewChart();
    initRatingDistributionChart();
  } else if (userStore.loginUser.role === 1) {
    // 校级管理员视角图表
    initYearlyTrendChart();
    initTestItemsChart();
    initClassesComparisonChart();
    initGradeDistributionChart();
    initGenderComparisonChart();
  } else {
    // 教育局管理员视角图表
    initYearlyTrendChart();
    initTestItemsChart();
    initRegionsComparisonChart();
  }
};

// 处理窗口大小变化
const handleResize = () => {
  // 班主任视角图表
  testQualificationChart?.resize();
  qualificationOverviewChart?.resize();
  ratingDistributionChart?.resize();
  
  // 校级管理员视角图表
  classesComparisonChart?.resize();
  gradeDistributionChart?.resize();
  genderComparisonChart?.resize();
  
  // 其他角色图表
  yearlyTrendChart?.resize();
  testItemsChart?.resize();
  regionsComparisonChart?.resize();
};

// 监听筛选条件变化
const handleFilterChange = () => {
  fetchDataPanelInfo();
};

// 组件挂载时
onMounted(() => {
  // 获取区域列表数据
  if (userStore.loginUser.role === 2) {
    fetchRegionOptions();
  }
  
  // 获取数据看板数据
  fetchDataPanelInfo();
  
  // 初始化图表
  initCharts();
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
});

// 页面销毁时
onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize);
  
  // 销毁图表实例
  yearlyTrendChart?.dispose();
  testItemsChart?.dispose();
  regionsComparisonChart?.dispose();
  testQualificationChart?.dispose();
  qualificationOverviewChart?.dispose();
  ratingDistributionChart?.dispose();
  classesComparisonChart?.dispose();
  gradeDistributionChart?.dispose();
  genderComparisonChart?.dispose();
});
</script>

<style scoped>
.data-board-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  overflow-y: auto;
  height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  display: flex;
  align-items: center;
}

.title h2 {
  margin: 0;
  margin-right: 15px;
  font-size: 22px;
  font-weight: bold;
}

.role-title {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #409EFF;
  cursor: pointer;
}

.search-bar {
  width: 300px;
}

.class-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.class-icon {
  margin-right: 15px;
  color: #409EFF;
}

.class-name {
  flex: 1;
}

.class-name h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.filters {
  display: flex;
  gap: 20px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 8px;
  font-size: 14px;
  color: #606266;
}

.overview {
  margin-bottom: 20px;
}

.overview-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.stats-overview {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
}

.stat-card {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  text-align: center;
  position: relative;
}

.stat-card .label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-card .value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.rate-change {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.rate-up {
  color: #67C23A;
  background-color: rgba(103, 194, 58, 0.1);
}

.rate-down {
  color: #F56C6C;
  background-color: rgba(245, 108, 108, 0.1);
}

.chart-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.chart {
  width: 100%;
  height: 300px;
}

.test-items-filter {
  margin-bottom: 15px;
}

.regions-container {
  margin-bottom: 20px;
}

.regions-comparison-filter {
  margin-bottom: 15px;
}

.test-item-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #409EFF;
  font-size: 14px;
}

.region-items {
  margin-top: 20px;
}

.region-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.region-name {
  width: 120px;
  font-size: 14px;
  color: #606266;
}

.region-progress {
  flex: 1;
  height: 8px;
  background-color: #f2f2f2;
  border-radius: 4px;
  overflow: hidden;
  margin: 0 15px;
}

.progress-bar {
  height: 100%;
  border-radius: 4px;
}

.region-rate {
  width: 50px;
  font-size: 14px;
  color: #303133;
  text-align: right;
  font-weight: bold;
}

.class-stats {
  margin-bottom: 20px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.teacher-charts {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.teacher-charts .chart-card {
  height: 400px;
}

.qualification-overview {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
}

.qualification-overview .chart {
  width: 100%;
  height: 65%;
}

.qualification-stats {
  width: 100%;
  padding-top: 20px;
  display: flex;
  justify-content: space-around;
}

.qualification-stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 15px;
}

.stat-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-bottom: 8px;
}

.stat-dot.qualified {
  background-color: #4e82ff;
}

.stat-dot.not-qualified {
  background-color: #ccc;
}

.region-container {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 可选：设置两个 div 之间的间距 */
}

.classes-container {
  margin-bottom: 20px;
}

.classes-comparison {
  margin-bottom: 15px;
}

.classes-comparison-filter {
  margin-bottom: 15px;
}

.class-items {
  margin-top: 20px;
}

.class-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.class-name {
  width: 120px;
  font-size: 14px;
  color: #606266;
}

.class-progress {
  flex: 1;
  height: 8px;
  background-color: #f2f2f2;
  border-radius: 4px;
  overflow: hidden;
  margin: 0 15px;
}

.progress-bar {
  height: 100%;
  border-radius: 4px;
}

.class-rate {
  width: 50px;
  font-size: 14px;
  color: #303133;
  text-align: right;
  font-weight: bold;
}

.grade-distribution {
  margin-bottom: 15px;
}

.gender-comparison {
  margin-bottom: 15px;
}
</style> 